package com.zlq.cn.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zlq.cn.entity.Movie;
import com.zlq.cn.entity.MovieComment;
import com.zlq.cn.mapper.movie.MovieMapper;
import com.zlq.cn.service.movie.MovieCategoryService;
import com.zlq.cn.service.movie.MovieCommentService;
import com.zlq.cn.service.movie.MovieService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhoucl
 * @date 2022/2/21 13:21
 */
@Slf4j
@Component
public class DouBanCommentUtils {
    private static final String DOU_BAN_SEARCH = "https://www.douban.com/search?q=%s";
    private static final String DOU_BAN_COMMENTS = "https://movie.douban.com/subject/%s/comments?start=0&limit=100&status=P&sort=new_score";
    private static DateTimeFormatter DF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private MovieCategoryService movieCategoryService;

    @Resource
    private MovieService movieService;

    @Resource
    private MovieCommentService movieCommentService;

    @Resource
    private MovieMapper movieMapper;

    static {
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
    }

    public void parse() {
        List<Movie> movies = movieMapper.selectNotComment();
        if (CollectionUtils.isNotEmpty(movies)) {
            WebDriver driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
            movies.forEach(movie -> {
                try {
                    driver.get(String.format(DOU_BAN_SEARCH, movie.getName()));
                    driver.get(driver.findElement(By.cssSelector(".result-list .result a")).getAttribute("href"));
                    String url = driver.getCurrentUrl();
                    url = url.substring(0, url.lastIndexOf("/"));
                    url = url.substring(url.lastIndexOf("/") + 1);
                    driver.get(String.format(DOU_BAN_COMMENTS, url));
                    Document document = Jsoup.parse(driver.getPageSource());
                    List<MovieComment> comments = document.select("#comments .comment-item").stream()
                            .map(element -> {
                                Element avatarEle = element.selectFirst(".avatar a");
                                String rating = null;
                                try {
                                    rating = element.selectFirst(".rating").attr("class").split(" ")[0].replace("allstar", "");
                                } catch (Exception e) {
                                    System.out.println("这个叼毛没有评分==》" + avatarEle.attr("title"));
                                }
                                return new MovieComment()
                                        .setMovieId(movie.getMovieId())
                                        .setAvatarName(avatarEle.attr("title"))
                                        .setAvatarHead(avatarEle.selectFirst("img").attr("src"))
                                        .setRating(rating)
                                        .setTime(LocalDateTime.parse(element.selectFirst(".comment-time").attr("title"), DF))
                                        .setContent(element.selectFirst(".short").text());
                            })
                            .collect(Collectors.toList());
                    movieCommentService.saveBatch(comments);
                } catch (Exception e) {
                    log.error(movie.getName());
                    log.error("获取出错", e);
                }
            });
            driver.quit();
        }
    }
}
